from sqlalchemy.ext.asyncio import AsyncSession as Session
from app.models.xm.xm_user import XmUser
from app.schemas.xm.xm_user import XmUserCreate, XmUserUpdate
from sqlalchemy import select

async def create_user_xm(session: Session, user_xm: XmUserCreate) -> XmUser:
    db_user_xm = XmUser(**user_xm.model_dump())
    session.add(db_user_xm)
    await session.commit()
    await session.refresh(db_user_xm)
    return db_user_xm

async def get_user_xm(session: Session, internal_uid: int) -> XmUser:
    db_user_xm = await session.execute(
        select(XmUser).where(XmUser.internalUid == internal_uid)
    )
    return db_user_xm.scalar_one_or_none()

async def update_user_xm(session: Session, internal_uid: int, user_xm: XmUserUpdate) -> XmUser:
    db_user_xm = await get_user_xm(session=session, internal_uid=internal_uid)
    if not db_user_xm:
        return None
    for key, value in user_xm.model_dump(exclude_unset=True).items():
        setattr(db_user_xm, key, value)
    session.add(db_user_xm)
    await session.commit()
    await session.refresh(db_user_xm)
    return db_user_xm